package com.psc.kpjy.view.utils;

import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Display;

import com.psc.kpjy.model.a.ContentListModelBean;
import com.psc.kpjy.view.ui.a.activity.VideoListActivity;
import com.psc.kpjy.view.ui.a.activity.WebViewInvitationActivity;
import com.psc.kpjy.model.utils.RefreshItem;
import com.psc.kpjy.view.ui.e.activity.LoginActivity;
import com.psc.kpjy.view.utils.dialog.DialogVideoActivity;
import com.psc.kpjy.view.utils.log.LogUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;

/**
 * Creator:Yx
 * Time:2020/8/14 14:15
 * Description:跳转
 */
public class ActivityUtils {

    /*
     * 是否更新我的界面用户信息
     */
    public static boolean isRefresh = true;

    /**
     * 是否允许截凴
     */
    public static boolean isScreenCapture = true;




    /*跳文章H5*/
    public static void toWebViewActivity(Context mContext, String aId, String mTitle) { // 相关推荐新详情页
        if (NoDoubleClickUtil.isFastClick()) return;
        mContext.startActivity(new Intent(mContext, WebViewInvitationActivity.class).putExtra("mInfo", aId)
                .putExtra("mName", mTitle));
    }

    /*跳文章H5-并是否关闭当前页*/
    public static void toWebViewActivityOnClose(Context mContext, String isClose, String aId, String mTitle) { // 相关推荐新详情页
        mContext.startActivity(new Intent(mContext, WebViewInvitationActivity.class).putExtra("mInfo", aId)
                .putExtra("mName", mTitle));
        if (!TextUtils.isEmpty(isClose) && "OFF".equals(isClose)) { // 关闭OFF，打开ON
            ((Activity) mContext).finish();
        }
    }

    /*跳一个新的未知 H5*/
    public static void toWebViewActivity(Context mContext, String isClose, String mTitle, String mUrl) { // 新打开某种页面
        mContext.startActivity(new Intent(mContext, WebViewInvitationActivity.class)
                .putExtra("mName", mTitle).putExtra("mUrl", mUrl));
        if (!TextUtils.isEmpty(isClose) && "OFF".equals(isClose)) { // 关闭OFF，打开ON
            ((Activity) mContext).finish();
        }
    }

    /*跳视频列表*/
    public static void toVideoListActivity(Context mContext, String vId, String mName) {
        if (NoDoubleClickUtil.isFastClick()) return;
        mContext.startActivity(new Intent(mContext, VideoListActivity.class).putExtra("vId", vId)
                .putExtra("mName", mName));
    }

    /*搜索结果跳视频列表*/
    public static void toVideoListBActivity(Context mContext, List<ContentListModelBean> mVideos, String mName) {
        mContext.startActivity(new Intent(mContext, VideoListActivity.class).putExtra("mVideos", (Serializable) mVideos)
                .putExtra("mName", mName));
    }

    /*打开视频窗口*/
    public static void showVideoDialog(Context mContext, String title, String thumbStr, String mUrl) {
        mContext.startActivity(new Intent(mContext, DialogVideoActivity.class).putExtra("mTitle", title)
                        .putExtra("mThumb", thumbStr).putExtra("mUrl", mUrl),
                ActivityOptions.makeSceneTransitionAnimation((Activity) mContext).toBundle());
    }

    /*打开登录窗*/
    public static void toLogins(Context mContext, String str) {
        mContext.startActivity(new Intent(mContext, LoginActivity.class).putExtra("mStr", str));
    }

    /**
     * 解析H5中的约定
     *
     * @param str prompt(js: // OpenNewDetails?aid=10&device=huawei,uid)
     */
    public static void analysisJs(Context mContext, String str, String defaultValue) {
        // 1.判断是否是JS
        int index = str.indexOf(":");
        String protocol = str.substring(0, index);
        if ("js".equals(protocol)) {
            LogUtil.iYx("-----Js_Prompt:拦截-----");
            // 2. 获取Url中的方法名
            String methodStr = "";
            // 3. 获取到Url中的参数
            String aid = "";
            String title = "";
            String thumbStr = "";
            String type = "";
            String mStr = "";
            String isClose = "";
            int indexEnd = str.indexOf("?");
            LogUtil.iYx("-----?号下标-------" + indexEnd);
            if (indexEnd < 0) {
                // 2.在Url中没有？号表示没有参数
                methodStr = str.substring(5); // 直接从5号下标截取到末尾
            } else {
                // 有参数
                // 2.截取到方法名
                methodStr = str.substring(5, indexEnd);
                // 3.截取到参数
                // 3.有参数,获取到拼接的完整参数：aid=10&device=huawei
                String dataStr = str.substring(indexEnd + 1);
                String[] dataAry = dataStr.split("&");
                // 参数集合
                HashMap<String, String> dataMap = new HashMap<>(dataAry.length);
                for (String d : dataAry) {
                    String[] mAry = d.split("=");
                    if (mAry.length == 2) {
                        dataMap.put(mAry[0], mAry[1]);
                    } else {
                        dataMap.put(mAry[0], "");
                    }
                }
                if (dataMap.size() > 0) {
                    aid = dataMap.get("aid");
                    title = dataMap.get("title");
                    thumbStr = dataMap.get("thumb");
                    type = dataMap.get("type");
                    mStr = dataMap.get("str");
                    isClose = dataMap.get("isClose");
                }
            }
            // 4.判断调用哪个方法
            if (methodStr.contains("OpenNewDetails")) {
                if (!TextUtils.isEmpty(aid)) { // prompt(js: // OpenNewDetails?aid=***&title=要显示标题,  "")
                    toWebViewActivityOnClose(mContext, isClose, aid, title);
                }
            } else if (methodStr.contains("OpenNewPage")) {
                if (!TextUtils.isEmpty(defaultValue)) { // prompt(js: // OpenNewPage?title=要显示标题&isClose=OFF  , "http: // 39.104.xx.xx:xxxx/xx/html/xxx.html?xx=xx&xx=xx")
                    defaultValue = getStringDecode(defaultValue);
                    toWebViewActivity(mContext, isClose, title, defaultValue);
                }
            } else if (methodStr.contains("showVideo")) {
                if (!TextUtils.isEmpty(defaultValue)) { // prompt(js: // showVideo?title=视频标题&thumb=视频封面 , "http: // 39.104.xx.xx:xxxx/xx/xxx/xxx.mp4")
                    thumbStr = getStringDecode(thumbStr);
                    defaultValue = getStringDecode(defaultValue);
                    showVideoDialog(mContext, title, thumbStr, defaultValue);
                }
            } else if (methodStr.contains("onUpdateSuccess")) {
                RefreshItem item = new RefreshItem(aid, mStr, defaultValue, type);
                EventBus.getDefault().post(item);
            } else if (methodStr.contains("toLogin")) {
                if (!TextUtils.isEmpty(defaultValue)) {
                    toLogins(mContext, defaultValue);
                }
            } else if (methodStr.contains("closePage")) {
                if (!TextUtils.isEmpty(defaultValue) && "OFF".equals(defaultValue)) { // prompt(js: // closePage , "OFF")
                    ((Activity) mContext).finish();
                }
            }
        }
    }


    /**
     * url解码
     * UTF-8
     *
     * @param str
     * @return
     */
    public static String getStringDecode(String str) {
        String result = "";
        try {
            if (!TextUtils.isEmpty(str)) {
                result = URLDecoder.decode(str, "UTF-8");
            } else {
                result = str;
            }
            LogUtil.iYx("Decode解码：" + result);
        } catch (Exception e) { // UnsupportedEncodingException
            result = str;
            LogUtil.iYx("Decode解码：" + result);
            // throw new RuntimeException(e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 更新某个Item
     * Type:1评论，2点赞，3收藏
     */
    public static int analysisContentList(List<ContentListModelBean> mLists, RefreshItem refreshItem) {
        int index = -1;
        if (mLists != null && mLists.size() > 0) {
            // for start
            for (int i = 0; i < mLists.size(); i++) {
                // 开始遍历
                if (mLists.get(i).getId().equals(refreshItem.getId())) {
                    if ("1".equals(refreshItem.getType())) {
                        // 评论numberOfComment
                        mLists.get(i).setNumberOfComment(refreshItem.getNum());
                    } else if ("2".equals(refreshItem.getType())) {
                        // 点赞
                        mLists.get(i).setLikes(refreshItem.getStr());
                        mLists.get(i).setNumberOfLike(refreshItem.getNum());
                    } else if ("3".equals(refreshItem.getType())) {
                        // 收藏
                        mLists.get(i).setFavorites(refreshItem.getStr());
                        mLists.get(i).setNumberOfFavorite(refreshItem.getNum());
                    } else {
                        LogUtil.iYx("未知操作");
                    }
                    index = i;
                    break;
                }
            }
            // for end
        }
        return index;
    }


    /**
     * 获取手机出厂时默认的densityDpi
     */
    public static int getDefaultDisplayDensity() {
        try {
            Class aClass = Class.forName("android.view.WindowManagerGlobal");
            Method method = aClass.getMethod("getWindowManagerService");
            method.setAccessible(true);
            Object iwm = method.invoke(aClass);
            Method getInitialDisplayDensity = iwm.getClass().getMethod("getInitialDisplayDensity", int.class);
            getInitialDisplayDensity.setAccessible(true);
            Object densityDpi = getInitialDisplayDensity.invoke(iwm, Display.DEFAULT_DISPLAY);
            return (int) densityDpi;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }


}
